package com.example.nextstream.api;


import com.alibaba.fastjson.JSONObject;
import com.example.nextstream.annotations.AuthRequired;
import com.example.nextstream.annotations.CurrentUser;
import com.example.nextstream.dto.SessionInfo;
import com.example.nextstream.models.AssetsInfo;
import com.example.nextstream.models.User;
import com.example.nextstream.service.ClientSessionService;
import com.example.nextstream.service.SessionStore;
import com.example.nextstream.utils.RspBuilder;
import org.apache.guacamole.GuacamoleException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/v1/clientSession")
public class ClientSessionAPi {
    @Autowired
    private SessionStore sessionStore;

    @Autowired
    private ClientSessionService clientSessionService;

    @RequestMapping("createSession")
    @AuthRequired
    @CrossOrigin
    public JSONObject createSession(@RequestParam("assetsId") Integer assetsId,@CurrentUser User user){
        String session = clientSessionService.createSession(assetsId,user.getId());
        return RspBuilder.createSuccessRsp().append("session_id",session).build();
    }
    @RequestMapping("getSessionInfo")
    @AuthRequired
    @CrossOrigin
    public JSONObject getSessionInfo(@RequestParam("sessionId") String sessionId){
        AssetsInfo assetsInfo = clientSessionService.getSessionByUUID(sessionId);
        return RspBuilder.createSuccessRsp().append("assets_info",assetsInfo).build();
    }

    @RequestMapping("listSession")
    @AuthRequired
    @CrossOrigin
    public JSONObject listSession(@CurrentUser User user) {
        List<SessionInfo> res = clientSessionService.listSession(user.getId());
        return RspBuilder.createSuccessRsp().append("sessions",res).build();
    }
    @RequestMapping("deleteSession")
    @AuthRequired
    @CrossOrigin
    public JSONObject deleteSession(@RequestParam("sessionId") String sessionId) {
        clientSessionService.deleteSession(sessionId);
        sessionStore.removeSessionObj(sessionId);

        return RspBuilder.createSuccessRsp().build();
    }

    @RequestMapping("closeSession")
    @AuthRequired
    @CrossOrigin
    public JSONObject closeSession(@RequestParam("sessionId") String sessionId) {
        sessionStore.removeSessionObj(sessionId);
        return RspBuilder.createSuccessRsp().build();
    }
    @RequestMapping("isSessionConnected")
    @AuthRequired
    @CrossOrigin
    public JSONObject isSessionActive(@RequestParam("sessionId") String sessionId) {
        return RspBuilder.createSuccessRsp().append("isActive",sessionStore.isSessionObj(sessionId)).build();
    }
}
